﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CSM.Protocol;

namespace CSMClient
{
	public partial class FormLogin : Form
	{
		/// <summary>
		/// 登入成功为TRUE
		/// </summary>
		public bool isLogin { get; set; }

		public FormLogin()
		{
			//注册数据包输入事件
			SocketManager.DataInput += new ZYSocket.ClientA.DataOn(SocketManager_DataInput);
			InitializeComponent();
			//测试关闭事件
			this.Closed += new EventHandler(LogOn_Closed);
			isLogin = false;
		}

        /// <summary>
        /// 输入包输入处理
        /// </summary>
        /// <param name="Data"></param>
		void SocketManager_DataInput(byte[] data)
		{
			UserToken token = new UserToken();
			ProtocolBase[] p = Protocol.Parser(data, ref token);
			if (p != null)
			{
				foreach (ProtocolBase item in p)
				{
					switch (item.Type)
					{
						case ProtocolWord.LoginResponse:
							{
								LoginResponse _resp = item as LoginResponse;
								if (_resp.Result == 0)	//登陆失败
								{
									isLogin = false; //设置 LOGINS
									MessageBox.Show(_resp.Message);
								}
								else if (_resp.Result == 1) //2登入成功
								{
									isLogin = true; //设置 LOGINS
									this.BeginInvoke(new EventHandler((o, e) => Close()));  //关闭窗口

									// 请求用户基本信息
//									SocketManager.client.SendTo(Protocol.Encode(new RequestUserInfo()));
								}
							}
							break;
// 						case ProtocolWord.RequestUserInfoResponse:
// 							{
// 								UserInfo = item as RequestUserInfoResponse;
// 								this.BeginInvoke(new EventHandler((o, e) => Close()));  //关闭窗口
// 							}
// 							break;
						default:
							break;
					}
				}
			}
		}
		
		void LogOn_Closed(object sender, EventArgs e)
		{
			//删除数据包输入事件
			SocketManager.DataInput -= new ZYSocket.ClientA.DataOn(SocketManager_DataInput);
		}

		private void btnLogin_Click(object sender, EventArgs e)
		{
			CSM.Protocol.Login temp = new CSM.Protocol.Login() //发送一个登入数据包
            {
				WorkID = this.textBox1.Text,
				Password = this.textBox2.Text
            };
			SocketManager.client.SendTo(Protocol.Encoder(temp));
		}
	}
}
